/*
 * Object.cpp
 *
 *  Created on: 2013-6-20
 *  Author: xnan
 */

#include "Object.h"
#include "AutoreleasePool.h"

NS_XNL_BEGIN

Object::Object()
: m_refcnt( 1 ),
  m_isAutorelease( false )
{
}

Object::Object( const Object & p_obj )
: m_refcnt( 1 ),
  m_isAutorelease( false )
{
}

Object::~Object()
{
    if( m_isAutorelease )
    {
        AutoreleasePool::instance()->removeObject( this );
    }
}

void Object::release()
{
    if( m_refcnt <= 0 ) throw std::runtime_error( XN_RUNTIME_ERR_STR( "object released, reference count '0'" ) );
    
    if( --m_refcnt <= 0 ) {
        delete this;
    }
}

void Object::retain()
{
    if( m_refcnt <= 0 ) throw std::runtime_error( XN_RUNTIME_ERR_STR( "object released, reference count '0'" ) );
    ++m_refcnt;
}

void Object::autorelease()
{
    if( !m_isAutorelease )
    {
        AutoreleasePool::instance()->addObject( this );
        m_isAutorelease = true;
        XN_RELEASE( this );
    }
}

XNcount Object::refCount() const
{
    return m_refcnt;
}

NS_XNL_END
